package com.qianbei.service;

/**
 * Created by gaoml on 2018/2/6.
 */
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.qianbei.bean.GetNamebean;
import com.qianbei.bean.GetRecord;
import com.qianbei.common.base.Basebean;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.log.LoggerInterceptor;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.orm.DaoMaster;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RequestPersistent;
import com.qianbei.view.orm.RequestPersistentDao;
import com.qianbei.view.transport.NameActivity;

import org.greenrobot.greendao.query.LazyList;
import org.greenrobot.greendao.query.QueryBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PushMsgService extends Service {
    // 轮询时间间隔
    private final static int MYTIME = 5 * 1000;
    //    private String url0 = "http://192.168.30.106:8067/";                                                 //请求的地址
    private String url0 = "http://192.168.110.168:82/";                      //正式服务                           //请求的地址
    private String url = url0 + "jsonapi/base/getService.json";
    private RequestPersistentDao persistentDao;
    private static final String TAG = PushMsgService.class.getSimpleName();
    private Gson mGson;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //LogUtil.e("test", "服务开始");
        startUpLoad();
//        startPushMsg();
//        start();
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mGson = new Gson();
        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        //内存重启后application缓存对象会被清除
        if (daoSession == null) {
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "gufei-db", null);
            SQLiteDatabase db = helper.getWritableDatabase();
            DaoMaster daoMaster = new DaoMaster(db);
            daoSession = daoMaster.newSession();
        }
        persistentDao = daoSession.getRequestPersistentDao();
    }

    private AtomicBoolean isUpload = new AtomicBoolean();
    /**
     * 启动push消息循环
     */
    private void startUpLoad() {
        isUpload.set(true);
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
//                            new PushMsg(getApplicationContext()).start();
                            long count = 0;
                            if (persistentDao != null) {
                                count = persistentDao.queryBuilder().count();
                            }
                            if (DeviceUtil.isNetworkAvailable() && count != 0 && isUpload.get()) {
                                QueryBuilder<RequestPersistent> queryBuilder = persistentDao.queryBuilder();
                                LazyList<RequestPersistent> persistentList = queryBuilder.build().listLazy();
                                if (persistentList.size() != 0) {
                                    postOkhttp(persistentList.get(0));
                                }
                            }
                            Thread.sleep(MYTIME);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, "push_msg").start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动push消息循环
     */
    private void startPushMsg() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
//                            new PushMsg(getApplicationContext()).start();
                            Log.d("pushMsgService", "llllllll----------------");
                            if (DeviceUtil.isNetworkAvailable() && MyApplication.netList.size() > 0) {
                                synchronized (MyApplication.netList) {
                                    for (RequeastBean bean : MyApplication.netList) {
                                        Log.d("pushMsgService", "aaaaa" + bean.toString());
                                        OKpost(bean);
                                    }
                                }
                            }


                            Thread.sleep(MYTIME);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, "push_msg").start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 222:
                    if (DeviceUtil.isNetworkAvailable() && MyApplication.netList.size() > 0) {

                        for (RequeastBean bean : MyApplication.netList) {
                            Log.d("gaoaaa", "aaaaa" + bean.toString());
                            ServerControl s = new ServerControl(bean);
                            s.OKpost2();
                        }
                    }
                    handler.sendEmptyMessageDelayed(222, MYTIME);
                    break;
            }

        }
    };

    private void start() {

        handler.sendEmptyMessage(222);
    }


    public static final MediaType FORM_CONTENT_TYPE
            = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

    public void OKpost(final RequeastBean mbean) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("token", SetData.getToken())
                                .addHeader(SetData.clientType,SetData.Android)
                                .build();
                        return chain.proceed(request);
                    }

                })
                .build();

//        Book book = new Book();
//        book.setName("android基础");
//        book.setPrice(59);
        //使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.1'
        Gson gson = new Gson();
        //使用Gson将对象转换为json字符串
        String json = gson.toJson(mbean);

        //MediaType  设置Content-Type 标头中包含的媒体类型值

        RequestBody requestBody = RequestBody.create(FORM_CONTENT_TYPE, "data=" + json);
//                FormBody.create(MediaType.parse("application/json; charset=utf-8"),"data="+json);


        Request request = new Request.Builder()
                .url(url)//请求的url
                .post(requestBody)
                .build();

        //创建/Call
        Call call = okHttpClient.newCall(request);
        //加入队列 异步操作
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                MyApplication.netList.remove(mbean);
            }
        });
    }

    public void postOkhttp(final RequestPersistent mbean) {
        isUpload.set(false);
        Log.d(TAG, "serviceBody:" + mbean.getServiceBody());
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(100, TimeUnit.SECONDS)
                .writeTimeout(100, TimeUnit.SECONDS)
                .readTimeout(200, TimeUnit.SECONDS)
                .addInterceptor(new LoggerInterceptor(TAG, true))
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("token", SetData.getToken())
                                .addHeader(SetData.clientType,SetData.Android)
                                //.addHeader("token", "admin990099509900995389900991990099null990099142619789372939900990019900992b15c65c1e0304a3dc14f9548892aaca")
                                .build();
                        return chain.proceed(request);
                    }

                })
                .build();
        String methodClass = mbean.getMethodClass();
        String json = "";
        try {
            Class<Basebean> clazz = (Class<Basebean>) Class.forName(methodClass);
            String serviceBody = mbean.getServiceBody();
            Basebean basebean = mGson.fromJson(serviceBody, clazz);
            String type = mbean.getType();
            //这里是把图片的路径转换成file再转为base64编码
            if ("1".equals(type)) {
                if (basebean instanceof GetNamebean) {
                    GetNamebean getNamebean = (GetNamebean) basebean;
                    ArrayList<String> photo_names = getNamebean.photo_names;
                    ArrayList<String> photo_ids = getNamebean.photo_ids;
                    ArrayList<String> photo_names_copy = new ArrayList<>();
                    photo_ids.clear();
                    for (String name : photo_names) {
                        try {
                            String id = NameActivity.encodeBase64File(name).replaceAll("[\\s*\t\n\r]", "");
                            String path = name.substring(name.lastIndexOf("/") + 1, name.length());
                            photo_names_copy.add(path);
                            photo_ids.add(id);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    getNamebean.photo_names = photo_names_copy;
                }
            } else if ("2".equals(type)) {
                if (basebean instanceof GetRecord) {
                    GetRecord getRecord = (GetRecord) basebean;
                    ArrayList<String> photo_names = getRecord.photo_names;
                    ArrayList<String> photo_ids = getRecord.p_id;
                    ArrayList<String> photo_names_copy = new ArrayList<>();
                    photo_ids.clear();
                    for (String name : photo_names) {
                        try {
                            String id = NameActivity.encodeBase64File(name).replaceAll("[\\s*\t\n\r]", "");
                            String path = name.substring(name.lastIndexOf("/") + 1, name.length());
                            photo_names_copy.add(path);
                            photo_ids.add(id);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    getRecord.photo_names = photo_names_copy;
                }
            }
            RequeastBean requeastBean = new RequeastBean(mbean.getServiceMethod(), mbean.getServiceName(), basebean);
            json = mGson.toJson(requeastBean);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            isUpload.set(true);
        }
//        Book book = new Book();
//        book.setName("android基础");
//        book.setPrice(59);
        //使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.1'
        //使用Gson将对象转换为json字符串
        RequestBody requestBody = RequestBody.create(FORM_CONTENT_TYPE, "data=" + json);
//                FormBody.create(MediaType.parse("application/json; charset=utf-8"),"data="+json);


        Request request = new Request.Builder()
                .url(url)//请求的url
                .post(requestBody)
                .build();

        //创建/Call
        Call call = okHttpClient.newCall(request);
        //加入队列 异步操作
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                isUpload.set(true);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                isUpload.set(true);
                if (response.isSuccessful()) {
                    try {
                        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
                        daoSession.getRequestPersistentDao().delete(mbean);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}